// MainDlg.h : interface of the CMainDlg class
//
/////////////////////////////////////////////////////////////////////////////

#pragma once
#include <atltypes.h>
#include <atlstr.h>
class CMainDlg : public CAxDialogImpl<CMainDlg>, public CUpdateUI<CMainDlg>,
	public CMessageFilter, public CIdleHandler,
	public IDispEventImpl<IDC_EXPLORER1,CMainDlg>
{
	HWND w;
	SHELLEXECUTEINFO sei;
	CEdit urledt;
	CComPtr<IWebBrowser2> m_pWB;
	CAxWindow2 axWnd;
	CListViewCtrl list;
	bool m_bRun;
public:
	enum { IDD = IDD_MAINDLG };

	virtual BOOL PreTranslateMessage(MSG* pMsg)
	{
		return CWindow::IsDialogMessage(pMsg);
	}

	virtual BOOL OnIdle()
	{
		if(!m_bRun)
			return FALSE;
		static int CurTime=0;
		static int LastTime = 0;
		CurTime=::GetTickCount();

		if(CurTime - LastTime>5000)
		{
			LastTime = CurTime;
			READYSTATE stat;
			m_pWB->get_ReadyState(&stat);
			if(stat != READYSTATE_COMPLETE)
			{
				return 0;
			}
			BSTR bstr;
			m_pWB->get_LocationURL(&bstr);
			CString s1 = bstr;
			CString s;
			GetDlgItemText(IDC_EDIT3,s);
			if(s1.CompareNoCase(s)!=0)
			{
				m_pWB->GoForward();
				m_pWB->get_ReadyState(&stat);
				if(stat != READYSTATE_COMPLETE)
				{
					return 0;
				}
			}
			if(list.GetItemCount()==0)
				ListLinkItem();
			static int n = 0;
			n++;
			
			s.Format(_T("%d"),n);
			SetWindowText(s);
			if (n%2==0)
			{
				IEClick();
			}
			else
			{
				wchar_t tmp[1001];
				this->GetDlgItemText(IDC_EDIT3,tmp,1000);
				CString tmpUrl = tmp;
				BSTR bstr = tmpUrl.AllocSysString();

				m_pWB->Navigate(bstr, NULL, NULL, NULL, NULL);
				SysFreeString(bstr);
			}
			if (n>20)
			{
				::ExitProcess(0);
			}
		}
		return FALSE;

	}

	BEGIN_UPDATE_UI_MAP(CMainDlg)
	END_UPDATE_UI_MAP()

	BEGIN_MSG_MAP(CMainDlg)
		CHAIN_MSG_MAP(CAxDialogImpl<CMainDlg>)
		MESSAGE_HANDLER(WM_TIMER, OnTimer)
		MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
		COMMAND_ID_HANDLER(IDOK, OnOK)
		COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
	END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
//	LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
//	LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
//	LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

	LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// center the dialog on the screen
		CenterWindow();

		// set icons
		HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
		SetIcon(hIcon, TRUE);
		HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
		SetIcon(hIconSmall, FALSE);

		// register object for message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->AddMessageFilter(this);
		pLoop->AddIdleHandler(this);

		UIAddChildWindowContainer(m_hWnd);
		this->SetTimer(1,500);
		this->SetDlgItemInt(IDC_EDIT1,10000);
		this->SetDlgItemInt(IDC_EDIT2,10000);
				axWnd = GetDlgItem(IDC_EXPLORER1);
		HRESULT hr;
		hr = axWnd.QueryControl(&m_pWB);
		if (hr != S_OK)
			return FALSE;
		this->SetDlgItemText(IDC_EDIT3,_T("http://www.163.com/"));
		//this->SetDlgItemText(IDC_EDIT4,_T("http://news.baidu.com/"));
		m_bRun = false;
		list=this->GetDlgItem(IDC_LIST1);
		list.SetViewType(LVS_REPORT);
		list.AddColumn(_T("link"),0);
		list.AddColumn(_T("position"),1);
		list.SetColumnWidth(0,180);
		list.SetColumnWidth(1,180);
		return TRUE;
	}

	LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// unregister message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->RemoveMessageFilter(this);
		pLoop->RemoveIdleHandler(this);

		return 0;
	}

	LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		//CAboutDlg dlg;
		//dlg.DoModal();
		CloseDialog(0);
		return 0;
	}

	LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		// TODO: Add validation code 
		//CloseDialog(wID);

		m_bRun =true;
		//int bOk = ShellExecuteEx(&sei);
		//if(bOk)
		//{
		wchar_t tmp[1001];
		this->GetDlgItemText(IDC_EDIT3,tmp,1000);
		CString tmpUrl = tmp;
		BSTR bstr = tmpUrl.AllocSysString();
				
		m_pWB->Navigate(bstr, NULL, NULL, NULL, NULL);
		SysFreeString(bstr);


		return 0;
	}

	LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		m_bRun = false;
		//CloseDialog(wID);
		return 0;
	}

	void CloseDialog(int nVal)
	{
		DestroyWindow();
		::PostQuitMessage(nVal);
	}
	void ListLinkItem()
	{
		list.DeleteAllItems();
		IDispatch* pDisp;
		//Get the underlying document object of the browser
		HRESULT hr1=m_pWB->get_Document(&pDisp);

		if (pDisp != NULL )
		{
			IHTMLDocument2* pHTMLDocument2;
			HRESULT hr;
			hr = pDisp->QueryInterface( IID_IHTMLDocument2,
				(void**)&pHTMLDocument2 );
			//Ask for an HTMLDocument2 interface
			if (hr == S_OK)
			{
				//Enumerate the HTML elements
				IHTMLElementCollection* pColl = NULL;
				hr = pHTMLDocument2->get_all( &pColl );
				if (hr == S_OK && pColl != NULL)
				{
					LONG celem;
					//Find the count of the elements
					hr = pColl->get_length( &celem );
					if ( hr == S_OK )
					{
						//Loop through each elment
						for ( int i=0; i< celem; i++ )
						{
							VARIANT varIndex;
							varIndex.vt = VT_UINT;
							varIndex.lVal = i;
							VARIANT var2;
							VariantInit( &var2 );
							IDispatch* pDisp; 
							hr = pColl->item( varIndex, 
								var2, &pDisp );//Get an element

							if ( hr == S_OK )
							{
								IHTMLElement* pElem;
								hr = pDisp->QueryInterface( 
									//Ask for an HTMLElemnt interface
									IID_IHTMLElement,
									(void **)&pElem);
								if ( hr == S_OK )
								{
									BSTR bstr;
									//Get the tag name for the element
									hr = pElem->get_tagName(&bstr);
									CString s = bstr;
									if(hr==S_OK && s.Compare(_T("A"))==0)
									{
										long left,top,width,height;
										pElem->get_offsetLeft(&left);
										pElem->get_offsetTop(&top);
										pElem->get_offsetWidth(&width);
										pElem->get_offsetHeight(&height);
										CRect rct;
										rct.left = left;
										rct.top = top;
										rct.bottom = top + height;
										rct.right = left+width;
										CPoint pt(this->GetDlgItemInt(IDC_EDIT1),this->GetDlgItemInt(IDC_EDIT2));
										pElem->get_innerHTML(&bstr);
										s= bstr;
										CString s1;
										s1.Format(_T("%d,%d,%d,%d"),left,top,width,height);
										list.AddItem(0,0,s);
										list.AddItem(0,1,s1);
										
									}
									pElem->Release();
								}
								pDisp->Release();
							}
						}
					}
					pColl->Release();
				}
				pHTMLDocument2->Release();
				//For the next page open a fresh document
			}
			pDisp->Release();
		}
	}
	void IEClick()
	{
		IDispatch* pDisp;
		//Get the underlying document object of the browser
		HRESULT hr1=m_pWB->get_Document(&pDisp);

		if (pDisp != NULL )
		{
			IHTMLDocument2* pHTMLDocument2;
			HRESULT hr;
			hr = pDisp->QueryInterface( IID_IHTMLDocument2,
				(void**)&pHTMLDocument2 );
			//Ask for an HTMLDocument2 interface
			if (hr == S_OK)
			{
				//Enumerate the HTML elements
				IHTMLElementCollection* pColl = NULL;
				hr = pHTMLDocument2->get_all( &pColl );
				if (hr == S_OK && pColl != NULL)
				{
					LONG celem;
					//Find the count of the elements
					hr = pColl->get_length( &celem );
					if ( hr == S_OK )
					{
						//Loop through each elment
						for ( int i=0; i< celem; i++ )
						{
							VARIANT varIndex;
							varIndex.vt = VT_UINT;
							varIndex.lVal = i;
							VARIANT var2;
							VariantInit( &var2 );
							IDispatch* pDisp; 
							hr = pColl->item( varIndex, 
								var2, &pDisp );//Get an element

							if ( hr == S_OK )
							{
								IHTMLElement* pElem;
								hr = pDisp->QueryInterface( 
									//Ask for an HTMLElemnt interface
									IID_IHTMLElement,
									(void **)&pElem);
								if ( hr == S_OK )
								{
									BSTR bstr;
									//Get the tag name for the element
									hr = pElem->get_tagName(&bstr);
									CString s = bstr;
									if(hr==S_OK && s.Compare(_T("A"))==0)
									{
										long left,top,width,height;
										pElem->get_offsetLeft(&left);
										pElem->get_offsetTop(&top);
										pElem->get_offsetWidth(&width);
										pElem->get_offsetHeight(&height);
										CRect rct;
										rct.left = left;
										rct.top = top;
										rct.bottom = top + height;
										rct.right = left+width;
										CPoint pt(this->GetDlgItemInt(IDC_EDIT1),this->GetDlgItemInt(IDC_EDIT2));
										if(rct.PtInRect(pt))
										{
											//MessageBox(_T("click"));
											pElem->click();
											pElem->Release();
											pDisp->Release();
											pColl->Release();
											return ;
										}
									}



									pElem->Release();
								}
								pDisp->Release();
							}
						}
					}
					pColl->Release();
				}
				pHTMLDocument2->Release();
				//For the next page open a fresh document
			}
			pDisp->Release();
		}
	}
public:
	LRESULT CMainDlg::OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// TODO: Add your message handler code here and/or call default
		
		return 1;
	}
public:
	BEGIN_SINK_MAP(CMainDlg)
		SINK_ENTRY(IDC_EXPLORER1, 273, NewWindow3Explorer1)
	END_SINK_MAP()
public:
	void __stdcall CMainDlg::NewWindow3Explorer1(LPDISPATCH* ppDisp, BOOL* Cancel, unsigned long dwFlags, BSTR bstrUrlContext, BSTR bstrUrl)
{
	// TODO: Add your message handler code here
	CString s = bstrUrl;
	if (s.Find(_T("."))>=0)
	{
		m_pWB->Navigate(bstrUrl,0,0,0,0);
	}

	* Cancel = true;
}
};
